package com.shengde.jinwawaforleader.network.photos;

import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.shengde.jinwawaforleader.HomeApplication;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.utils.PictureUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ProImageUpload {
	private static final String TAG = "ProImageUpload";
	public static boolean saveBitmapFile(Bitmap bitmap, String newFilename) {
		File file = new File(newFilename);
		BufferedOutputStream bos = null;
		try {
			if (file.exists())
				file.delete();
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bitmap.compress(Bitmap.CompressFormat.PNG, 40, bos);
			bos.flush();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bos != null)
					bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	public static final String TMP_FILE = "tmp.png";
	public static File dir = null;

	public static String getNewName(String path) {
		if (dir == null)
//			dir = HomeApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
			dir = HomeApplication.getInstance().getFilesDir(); //罗春写的，之前的保存地址
		if (!dir.exists()) {
			dir.mkdirs();
		}
		if (TextUtils.isEmpty(path))
			return null;
		if (!path.contains("."))
			return null;
		File f = new File(path);
		String filename = f.getName();
		int index = filename.lastIndexOf(".");
		//String prefix = filename.substring(0, index);	//罗春写的，前缀名
		String suffix = filename.substring(index);
		Log.e(TAG, dir.getAbsolutePath() + File.separator + System.currentTimeMillis() + suffix);
		return dir.getAbsolutePath() + File.separator + System.currentTimeMillis() + suffix;
	}

	public static String getTmpFilename() {
		if (dir == null)
			dir = HomeApplication.getInstance().getFilesDir();
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir.getAbsolutePath() + File.separator + TMP_FILE;
	}

	// 同步线程
	@SuppressWarnings("deprecation")
	public static String upload(String filename) {
		HttpClient httpClient = null;
		File newFile = null;
		try {
			//+ "/parent/ImageUpload"
//			String url = BaseProtocol.YU_MING ;
			String url = "http://www.kingvar.com:8080/api/parent/ImageUpload/";

			HttpPost httpPost = new HttpPost(url);

			System.out.println("post url:" + url);

			httpPost.setHeader("User-Agent", "SOHUWapRebot");

			httpPost.setHeader("Accept-Language", "zh-cn,zh;q=0.5");

			httpPost.setHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.7");

			httpPost.setHeader("Connection", "keep-alive");

			MultipartEntity mutiEntity = new MultipartEntity();
              
			File file = new File(filename);
			Log.i(TAG, "upload: lenth = " + file.length());
			if (file.length() > 50 * 1024) {
				Bitmap newBitmap = PictureUtil.getSmallBitmap(filename);
				String newname = getNewName(filename);
				if (newBitmap != null && saveBitmapFile(newBitmap, newname))
					newFile = new File(newname);
				Log.i(TAG, "upload: newFilelenth = " + newFile.length());
				Log.i(TAG, "upload: newBitmap = " + newBitmap);

			}

			//mutiEntity.addPart("file", new FileBody(newFile == null ? file
			mutiEntity.addPart("pic", new FileBody(newFile == null ? file
					: newFile));

			httpPost.setEntity(mutiEntity);
			httpClient = new DefaultHttpClient();
			HttpResponse httpResponse = httpClient.execute(httpPost);

			HttpEntity httpEntity = httpResponse.getEntity();

			String content = EntityUtils.toString(httpEntity);
			JSONObject json = new JSONObject(content);
			if (json.optInt("code") != 0)
				return null;
			JSONArray arr = json.optJSONArray("url");
			if (arr == null || arr.length() < 1)
				return null;
			return arr.optString(0);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (newFile != null)
				newFile.delete();
			httpClient.getConnectionManager().shutdown();
		}
		return null;
	}
}